package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private TravelCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    public TravelComment saveOrUpdate(TravelComment comment) {
        comment.setCreateTime(new Date());
        //如果是 评论的评论 , 需要额外处理
        if (comment.getType() == TravelComment.TRAVLE_COMMENT_TYPE) {
            String refId = comment.getRefComment().getId();
            if (StringUtils.hasLength(refId)) {
                //判断是否有评论的评论
                TravelComment refComment = repository.findById(refId).get();
                comment.setRefComment(refComment);
            }
        }
        repository.save(comment);
        return comment;
    }

    public Page query(TravelCommentQuery qo) {
        Query query = new Query();
        //查询指定评论明细的评论
        if (qo.getTravelId() != -1) {
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
        //注意  此时total为指定明细的所有评论  所以不能有分页条件
        long total = template.count(query, TravelComment.class);
        //分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "createTime");
        query.with(pageable);
        List<TravelComment> list = template.find(query, TravelComment.class);

        return new PageImpl(list, pageable, total);
    }

    public Long getCount(Long travelId) {
        Query query = new Query();
        if (travelId != -1) {
            query.addCriteria(Criteria.where("travelId").is(travelId));
        }
        return template.count(query, TravelComment.class);
    }

    public List<TravelComment> queryCommentForTen(TravelCommentQuery qo) {
        Query query = new Query();
        //查询所有的评论
        //分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        query.with(pageable);
        return template.find(query,TravelComment.class);
    }
}
